//
//  WmcBaseVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/1.
//

import YPKeyboardManager
import UIKit
import YPBedrock

public extension WmcBaseVC {
    enum NavStyle {
        /// 白色
        case white
        /// 深色
        case dark
        /// 透明的
        case transparent(tintColor: UIColor)
    }
}

// MARK: - [WmcBaseVC]

open class WmcBaseVC: UIViewController {
    // Lifecycle
    
    // 标记回到特定页
    var popToVCMark: Bool = false
    // 导航栏细线
    lazy var naviLineView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH15_E6E6E6
        return view
    }()
    
    override open func viewDidLoad() {
        lifeCycleLog("\(self.yp.className)进入了‘viewDidLoad’")
        super.viewDidLoad()
        view.backgroundColor = .white
        makeUI() // 先进行布局
        bindViewModel() // 反向数据流绑定
        bindViewAction() // 正向数据流绑定
        bindDriving() // 驱动数据流绑定

        let classType = Self.self as? WmcNavigatorProtocol.Type
        vcDelegate?.viewDidLoad(.current, navigationPath: classType?.navigationPaths())
    }

    deinit {
//        WmcLogManager.DebugLog(type: .delloc, log: "VC被释放\(self)")
        print("😍😍😍VC被释放\(self)")
    }

    override open func viewWillAppear(_ animated: Bool) {
        lifeCycleLog("\(self.yp.className)进入了‘viewWillAppear’")
        super.viewWillAppear(animated)
        WmcNotice.Post(WmcLifeCycleProtocol.self) { [weak self] t in
            guard let weakSelf = self else { return }
            t.viewWillAppear(weakSelf)
        }
        let classType = Self.self as? WmcNavigatorProtocol.Type
        vcDelegate?.viewWillAppear(.current, navigationPath: classType?.navigationPaths())

        IQKeyboardManager.shared.enable = keyboardManagerEnable
    }

    override open func viewDidAppear(_ animated: Bool) {
        lifeCycleLog("\(self.yp.className)进入了‘viewDidAppear’")
        super.viewDidAppear(animated)
        WmcNotice.Post(WmcLifeCycleProtocol.self) { [weak self] t in
            guard let weakSelf = self else { return }
            t.viewDidAppear(weakSelf)
        }
        let classType = Self.self as? WmcNavigatorProtocol.Type
        vcDelegate?.viewDidAppear(.current, navigationPath: classType?.navigationPaths())
    }

    override open func viewWillDisappear(_ animated: Bool) {
        lifeCycleLog("\(self.yp.className)进入了‘viewWillDisappear’")
        super.viewWillDisappear(animated)
        WmcNotice.Post(WmcLifeCycleProtocol.self) { [weak self] t in
            guard let weakSelf = self else { return }
            t.viewWillDisappear(weakSelf)
        }
        let classType = Self.self as? WmcNavigatorProtocol.Type
        vcDelegate?.viewWillDisappear(.current, navigationPath: classType?.navigationPaths())
    }

    override open func viewDidDisappear(_ animated: Bool) {
        lifeCycleLog("\(self.yp.className)进入了‘viewDidDisappear’")
        super.viewDidDisappear(animated)
        WmcNotice.Post(WmcLifeCycleProtocol.self) { [weak self] t in
            guard let weakSelf = self else { return }
            t.viewDidDisappear(weakSelf)
        }
        let classType = Self.self as? WmcNavigatorProtocol.Type
        vcDelegate?.viewDidDisappear(.current, navigationPath: classType?.navigationPaths())
    }

    // Open

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return statusBarStyle
    }

    /// 标题
    override open var title: String? {
        set { navView.title = newValue }
        get { return navView.title }
    }

    /// 禁用三指键盘撤回
    @available(iOS 13.0, *)
    override open var editingInteractionConfiguration: UIEditingInteractionConfiguration {
        return .none
    }

    override open func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if isNavViewLoad { // 如果加载了导航条视图，则每次布局前将其前置
            view.bringSubviewToFront(navView)
        }
    }

    // Internal

    static var NavHeight: CGFloat { 50 + Wmc_statusBarHeight }

    /// 自定义导航条
    lazy var navView: WmcNavView = {
        let navView = WmcNavView()
        navView.backControl.addTarget(self, action: #selector(self.backAction), for: .touchUpInside)
        return navView
    }()

    /// 用于处理延迟执行的对象
    /// 防止多个执行者相互取消冲突的问题
    lazy var _nextResponder: NSObject = {
        let obj = NSObject()
        return obj
    }()

    /// 状态栏颜色
    var statusBarStyle: UIStatusBarStyle = .default

    /// 导航视图
    var navigationVC: WmcNavVC? {
        guard let nav = navigationController as? WmcNavVC else { return nil }
        return nav
    }

    var vcDelegate: WmcViewControllerDelegate? {
        return YPWmcManager.shared.uiDelegate.viewControllerDelegate
    }

    var keyboardManagerEnable: Bool = true {
        didSet {
            IQKeyboardManager.shared.enable = keyboardManagerEnable
            IQKeyboardManager.shared.shouldResignOnTouchOutside = keyboardManagerEnable
        }
    }

    /// 返回的操作事件
    @objc
    func backAction() {
        popVC()
    }

    /// pop返回
    func popVC(style: WmcTransition.Style? = nil,
               animated: Bool = true,
               completion: YPBlock.Empty? = nil)
    {
        if let navVC = navigationController as? WmcNavVC {
            navVC.wmc_pop(style: style, animated: animated, completion: completion)
        } else {
            navigationController?.popViewController(animated: animated)
        }
    }

    /// dismiss返回
    func dismissVC(animated: Bool = true) {
        dismiss(animated: true, completion: nil)
    }

    /// 创建导航
    func makeNavView(style: NavStyle = .white, showShadow: Bool = true) {
        switch style {
        case .white:
            navView.backgroundColor = .white
            navView.backImageView.yp.set(tintColor: UIColor.wmc_grayH2_323233)
            navView.titleLabel.textColor = .wmc_grayH2_323233
            statusBarStyle = .default
        case .dark:
            navView.backgroundColor = .black
            navView.backImageView.yp.set(tintColor: UIColor.white)
            navView.titleLabel.textColor = .white
            statusBarStyle = .lightContent
        case let .transparent(tintColor):
            navView.backgroundColor = .clear
            navView.backImageView.yp.set(tintColor: tintColor)
            navView.titleLabel.textColor = tintColor
            statusBarStyle = .default
        }
        setNeedsStatusBarAppearanceUpdate()
        isNavViewLoad = true
        addSubview(navView)
        navView.layer.zPosition = 10 // 永远前置
        navView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(Self.NavHeight)
        }
        if showShadow {
            navView.addShadow()
        }
    }

    /// 导航条使用关闭按钮
    func navViewSetCloseImage() {
        navView.backImageView.image = "close".wmc_image
        navView.backImageView.snp.remakeConstraints { make in
            make.top.equalTo(Wmc_statusBarHeight)
            make.bottom.equalToSuperview()
            make.left.equalTo(Wmc_standardEdge.left * 2)
            make.width.equalTo(18)
        }
    }

    /// 正向数据流（页面操作的监听）方法放在这里
    func bindViewAction() {}

    /// 反向数据流（ViewModel的监听）进行数据绑定的放在这里
    func bindViewModel() {}

    /// 驱动数据流（外部业务要求执行内部方法），如果有需要绑定的，则实现该方法
    func bindDriving() {}

    /// 创建UI的方法放在这里
    /// 最好按照，从上至下，从左至右依次添加视图
    func makeUI() {}

    /// 方便添加视图
    func addSubview(_ subView: UIView) {
        view.addSubview(subView)
    }

    // Fileprivate

    /// navView是否加载
    fileprivate var isNavViewLoad: Bool = false

    /// 生命周期日志系统
    fileprivate func lifeCycleLog(_ log: String) {
        WmcLogManager.DebugLog(type: .lifeCycle, log: log)
    }
}
